package jbase.project.system.net.http.management;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import jbase.project.system.core.common.EventHook;
import jbase.project.system.net.http.HttpResponseHeaders;

public class HttpResponseHook implements EventHook {
	private OutputStream out;
	private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
	private boolean end = false;

	public HttpResponseHook(OutputStream out) {
		this.out = out;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T, R> R event(String event, T... objects) {
		if (!end) {
			if (event.equals("out")) {
				String content = (String) objects[0];
				try {
					buffer.write(content.getBytes());
					buffer.flush();
				} catch (IOException e) {
				}
			} else if (event.equals("end")) {
				HttpResponseHeaders responseHeaders = new HttpResponseHeaders();
				responseHeaders.setResponseStatus(200);
				byte[] content = this.buffer.toByteArray();
				responseHeaders.setConentLength(content.length);
				try {
					out.write(responseHeaders.toString().getBytes());
					out.write(content);
					out.flush();
				} catch (Exception e) {

				} finally {
					this.end = true;
					try {
						this.out.close();
					} catch (Exception e) {
					}
				}
			}
		}
		return null;
	}
}